import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { UserEntity } from "../users/entity/user.entity";
import { Connection, Repository } from "typeorm";
import { FileEntity } from "./entity/file.entity";
import { UploadAddDto } from "./dto/upload-add.dto";
import { createWriteStream, existsSync, unlinkSync } from "fs";
import { join } from "path";
import { format } from "date-fns";

@Injectable()
export class UploadService {
  constructor(
    private connection: Connection,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(FileEntity)
    private readonly fileRepository: Repository<FileEntity>
  ) {
  }

  async userAvatarUpload(userInfo, dto: UploadAddDto, uploadFile) {
    const queryRunner = this.connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      //定义文件基础属性
      const uploadPath = "../../../public/avatar/";
      //文件名
      const fileName = `avatar-${userInfo.id}`;
      //文件类型
      const fileType = uploadFile.mimetype.split("/")[1];
      //用来输入输出流
      const uploadName = `${fileName}.${fileType}`;
      //写入文件
      // 判断文件是否存在
      const isFileExists = await this.fileRepository.findOne({ where: { name: fileName } });
      //设置文件属性
      const _file = new FileEntity();
      _file.name = fileName;
      _file.useType = dto.useType;
      _file.createTime = format(new Date(), "yyyy-MM-dd HH:mm:ss");
      _file.type = fileType;
      _file.path = "/static/avatar/" + uploadName;
      _file.status = 1;
      let fileRes = null;
      //文件写入
      if (isFileExists) {
        //如果文件存在
        fileRes = await this.fileRepository.update({ name: isFileExists.name }, _file);
        this.writeStream(join(__dirname, uploadPath, uploadName), uploadFile.buffer);
      } else {
        //如果文件不存在
        fileRes = await this.fileRepository.save(_file);
        this.writeStream(join(__dirname, uploadPath, uploadName), uploadFile.buffer);
      }
      // 导入到用户信息中
      const res = await this.userRepository.update({ id: userInfo.id }, { avatar: fileRes.id ? fileRes.id.toString() : isFileExists.id.toString() });
      // 提交事务
      await queryRunner.commitTransaction();
      return res;
    } catch (e) {
      console.log(e);
    }

  }

  //通过uuid获取文件
  async getFile(dto) {
    const file = new FileEntity();
    file.id = dto.uuid;
    return await this.fileRepository.findOne({ where: file });
  }

  //文件流传输
  writeStream(path, stream) {
    if (existsSync(path)) {
      unlinkSync(path);
    }
    console.log(existsSync(path));
    //文件不存在就写入
    const writeStream = createWriteStream(path);
    writeStream.write(stream);
  }

}
